# -*- coding: UTF-8 -*-
# @Author  : icedew
# @File    : views.py
# @Time    : 2019-4-29 17:17
import random
import string

from flask import Blueprint, views, render_template, request, session, redirect, url_for, g, jsonify
from flask_login import login_user, current_user, logout_user
from flask_mail import Message

import config
from apps.cms.forms import LoginForm, ResetPwdForm, RestEmailForm
from apps.cms.decorators import login_required
from apps.cms.models import CMSUser
from apps.utils import xjson, xcache
from exts import db, mail

bp = Blueprint("cms",__name__,url_prefix='/cms')

@bp.route('/')
def index():
    return render_template("cms/cms_index.html")

class LoginView(views.MethodView):
    def get(self, message=None):
        form = LoginForm()
        return render_template('cms/cms_login.html',form=form)

    def post(self):
        form = LoginForm()
        if form.validate_on_submit():
            user = CMSUser.query.filter_by(email=form.email.data).first()
            if user and user.check_password(form.password.data):
                session[config.CMS_USER_ID] = user.id
                if form.remember_me.data:
                    # 如果勾选了记住我，则保存session,这样就算浏览器关闭session还是存在的
                    session.permanent = True
                return redirect(url_for('cms.index'))
            else:
                # return render_template('cms/cms_login.html', message='账号或密码错误')
                # 等同于以下代码
                # return self.get(message='账号或密码错误')
                return render_template("cms/cms_login.html", form=form, loginError="账号或密码错误")
        else:
            # form.errors的错误信息格式，是一个字典，value是列表的形式
            # {'email': ['请输入正确的邮箱格式'], 'password': ['密码长度不够或超出']}
            message = form.errors.popitem()[1][0]
            return render_template("cms/cms_login.html", form=form, loginError=message)

@bp.route('/logout/')
@login_required
def logout():
    del session[config.CMS_USER_ID]
    return redirect(url_for('cms.login'))

@bp.route('/profile/')
@login_required
def profile():
    return render_template('cms/cms_profile.html')

class ResetPwdView(views.MethodView):
    decorators = [login_required]
    def get(self):
        return render_template('cms/cms_resetpwd.html')

    def post(self):
        resetpwd_form = ResetPwdForm(request.form)
        if resetpwd_form.validate():
            oldpwd = resetpwd_form.oldpwd.data
            newpwd = resetpwd_form.newpwd.data
            user = g.cms_user
            if user.check_password(oldpwd):
                user.password = newpwd
                db.session.commit()
                return xjson.json_success('修改成功')
            else:
                return  xjson.json_params_error('原密码错误')
        else:
            message = resetpwd_form.get_error()
            return xjson.json_params_error(message)

class ResetEmailView(views.MethodView):
    decorators = [login_required]
    def get(self):
        return render_template('cms/cms_resetemail.html')

    def post(self):
        resetemail_form = RestEmailForm(request.form)
        if resetemail_form.validate():
            email = resetemail_form.email.data
            g.cms_user.email = email
            db.session.commit()
            return xjson.json_success('邮箱修改成功')
        else:
            message = resetemail_form.get_error()
            return xjson.json_params_error(message)

@bp.route('/email/')
def send_email():
    #1.标题，2.收件人，3.发送的正文内容
    message = Message(subject='derek论坛密码修改邮件发送',recipients=['1184405959@qq.com',],body='第一次测试发送邮件')
    mail.send(message)    #发送邮件
    return '邮件发送成功'

@bp.route('/email_captcha/')
@login_required
def email_captcha():
    #/cms/emai_capthcha/?email=xxxx@qq.com
    email = request.args.get('email')
    if not email:
        return xjson.json_params_error('请传递邮件参数！')

    #生成6位数的随机验证码
    source = list(string.ascii_letters)
    source.extend(map(lambda x:str(x), range(0,10)))
    captcha = ''.join(random.sample(source, 6))

    #发送邮件
    msg = Message('BBS论坛更换邮箱验证码',
                  recipients=[email],
                  body='您的验证码：{},5分钟内有效'.format(captcha))
    try:
        mail.send(msg)
    except Exception as err:
        print(err)
        return xjson.json_server_error(message='邮件发送失败')

    #验证码存入memcached
    xcache.set(email, captcha)
    return xjson.json_success(message='邮件发送成功')

bp.add_url_rule('/login/',view_func=LoginView.as_view('login'))
bp.add_url_rule('/resetpwd/',view_func=ResetPwdView.as_view('resetpwd'))
bp.add_url_rule('/resetemail/', view_func=ResetEmailView.as_view('resetemail'))